<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left" size="mini">

      <div class="title-container">
        <h3 class="title">后台管理系统</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.username"
          placeholder="账号"
          name="username"
          type="text"
          tabindex="1"
          autocomplete="on"
          @keyup.enter.native="handleLogin"
        />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input
            :key="passwordType"
            ref="password"
            v-model="loginForm.password"
            :type="passwordType"
            placeholder="密码"
            name="password"
            tabindex="2"
            autocomplete="on"
            @keyup.native="checkCapslock"
            @blur="capsTooltip = false"
            @keyup.enter.native="handleLogin"
          />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>

      <el-form-item prop="captcha" class="login-captcha">
        <span class="svg-container">
          <svg-icon icon-class="valid-code" />
        </span>
        <el-input
          ref="captcha"
          v-model="loginForm.captcha"
          placeholder="验证码"
          name="username"
          type="text"
          tabindex="1"
          @keyup.enter.native="handleLogin"
        />
        <div class="captcha">
          <img :src="captchaUrl" title="点击刷新验证码" @click="refreshCaptcha">
        </div>
      </el-form-item>

      <el-checkbox v-model="rememberPassword" class="remember-password">记住密码</el-checkbox>

      <el-button :loading="loading" type="primary" style="width:100%;" @click.native.prevent="handleLogin">登 录</el-button>
    </el-form>
  </div>
</template>

<script>
import { isEmpty, isBlank } from '@/utils/validate'
import { saveLStorage, getLStorage, delLStorage } from '@/utils/index'
import { captcha } from '@/api/auth'

export default {
  name: 'Login'
  , data() {
    const validateUsername = (rule, value, callback) => {
      if (isEmpty(value) || isBlank(value)) {
        callback(new Error('请输入账号'))
      } else if (value.length < 4 || value.length > 32) {
        callback(new Error('账号错误，请重新输入'))
      } else {
        callback()
      }
    }

    const validatePassword = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback(new Error('请输入密码'))
      } else if (value.length < 4 || value.length > 64) {
        callback(new Error('密码错误，请重新输入'))
      } else {
        callback()
      }
    }

    const validateCaptcha = (rule, value, callback) => {
      if (isEmpty(value) || isBlank(value)) {
        callback(new Error('请输入验证码'))
      } else if (value.length < 1 || value.length > 8) {
        callback(new Error('验证错误，请重新输入'))
      } else {
        callback()
      }
    }
    return {
      captchaUrl: 'https://www.oschina.net/action/user/captcha'
      , rememberPassword: false
      , rememberPasswordKey: 'remember-password-key'
      , loginForm: {
        captchaKey: ''
        , username: 'admin'
        , password: '12345678'
        , captcha: ''
      }
      , loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }]
        , password: [{ required: true, trigger: 'blur', validator: validatePassword }]
        , captcha: [{ required: true, trigger: 'blur', validator: validateCaptcha }]
      }
      , passwordType: 'password'
      , capsTooltip: false
      , loading: false
      , redirect: undefined
    }
  }
  , watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
        }
      }
      , immediate: true
    }
  }
  , created() {
    // 处理记住密码
    const data = getLStorage(this.rememberPasswordKey)
    if (!!data && data['username'] && data['password']) {
      this.rememberPassword = true
      this.loginForm.username = data['username']
      this.loginForm.password = data['password']
    }

    // 获取验证码数据
    this.refreshCaptcha()
  }
  , mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  }
  , methods: {
    // 本地存储数据
    rememberPasswordAction() {
      if (this.rememberPassword && this.loginForm.username && this.loginForm.password) {
        saveLStorage(this.rememberPasswordKey, this.loginForm)
      } else {
        delLStorage(this.rememberPasswordKey)
      }
    }
    // 刷新验证码
    , refreshCaptcha() {
      captcha().then(response => {
        this.captchaUrl = response.data.img
        this.loginForm.captchaKey = response.data.key
      }).catch(err => {
        console.error('验证码获取失败：', err)
      })
    }
    , checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    }
    , showPwd() {
      this.passwordType = this.passwordType === 'password' ? '' : 'password'
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    }
    , handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              // 记住密码
              this.rememberPasswordAction()
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('提交错误!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss">
$bg: #fff;
$fontColor: #606266;

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 10px 5px 10px 15px;
      height: 36px;
      color: $fontColor;
      caret-color: $fontColor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $fontColor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid #dcdfe6;
    background: $bg;
    border-radius: 5px;
    color: $fontColor;
    margin-bottom: 1.35em;

    .el-form-item__error {
      padding-top: 4px;
    }
  }
}
</style>

<style lang="scss" scoped>
$bg:#2d3a4b;
$dark_gray:#889aa4;
$light_gray:#eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  background-image: url("http://vue.ruoyi.vip/static/img/login-background.f9f49138.jpg");
  background-size: cover;

  .login-form {
    background-color: #ffffff;
    position: fixed;
    left: calc((100vw - 400px) / 2);
    top: calc((100vh - 370px) / 2);
    width: 400px;
    height: 370px;
    border-radius: 6px;
    padding: 0 25px;

    .title-container .title {
      font-size: 1.5em;
      color: #707070;
      text-align: center;
      font-weight: bold;
    }

    .login-captcha{
      width: calc(100% - 138px);
    }

    div.captcha {
      position: absolute;
      right: -138px;
      top: 0;
      width: 120px;
      border: 1px solid #dcdfe6;
      border-radius: 5px;
      overflow: hidden;
      height: 40px;
      img{
        width: 100%;
        height: 40px;
        cursor: pointer;
      }
    }

    .remember-password {
      margin-bottom: 1.35em;
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
